<?php
namespace app\car\model;
use think\Model;
use think\Db;

class Pool extends Model
{
    public function getListByCategory($pid,$pageno,$pagesize)
    {
        $newDate = time();
        $start = ($pageno-1)*$pagesize;
        if($pid != 0){//不等于就是分类查询
            $pools = Db::table("car_pool_info")->where("status=1 and category={$pid} and unix_timestamp(departure_time)>={$newDate}")->order("id desc")->limit($start,$pagesize)->select();
            $category = Db::table("car_category")->where("status=1 and id={$pid}")->order("id asc")->find();
        }else{
            $pools = Db::table("car_pool_info")->where("status=1 and unix_timestamp(departure_time)>={$newDate}")->order("id desc")->limit($start,$pagesize)->select();
            $category = Db::table("car_category")->where("status=1")->order("id asc")->select();
        }

        foreach ($pools as $k=>$pool) {
            if($pid != 0){
                $pools[$k]['category_name'] = $category['category_name'];
            }else{
                foreach ($category as $cate) {
                    if($pool['category'] == $cate['id']){
                        $pools[$k]['category_name'] = $cate['category_name'];
                    }
                }
            }

            $pools[$k]['car_img'] = explode(",",$pool['car_img']);
            $pools[$k]['tag'] = explode(",",$pool['tag']);
        }
        $result = $pools;
        return $result;
    }
    public static function poolAdd($data)
    {
        $data['update_time'] = date("Y-m-d H:i:s");
        $data['date'] = date("Y-m-d");
		if(isset($data['car_img'])){
			$data['car_img'] = implode(",",$data['car_img']);
		}
        $data['tag'] = implode(",",$data['tag']);
        $res = Db::table("car_pool_info")->insert($data);
        return $res;
    }
    public function myCarPoolEdit($data)
    {
        $data['update_time'] = date("Y-m-d H:i:s");
        $res = Db::table("car_pool_info")->where("id={$data['id']}")->update($data);
        return $res;
    }
    public function poolDetail($id)
    {
        $result = Db::table("car_pool_info")->alias("a")
            ->join("car_category b","a.category=b.id","left")
            ->where("a.id={$id} and a.status=1")
            ->field(["a.*","b.category_name"])
            ->find();
        $result['tag_name'] = Db::table("car_tag")->where("id in ({$result['tag']})")->field("id,tag_name")->select();
        $result['comment'] = model("Comment")->getCommentListByCid($id);
        return $result;
    }
    public function myPoolList($pageno,$pagesize)
    {
        $uid = 1;
        $start = ($pageno-1)*$pagesize;
        $result = Db::table("car_pool_info")->where("uid={$uid} and status!=6")->order("id desc")->limit($start,$pagesize)->select();
        return $result;
    }
    public function myPooldel($id)
    {
        $uid = 1;
        $res = Db::table("car_pool_info")->where("id={$id} and uid={$uid}")->setField("status",6);
        return $res;
    }
}